package com.wly.dbc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import com.wly.dbc.parser.BaseParser;
import com.wly.define.ParserDefine;

public class ParserFactory
{
	private static ParserFactory _instance = null;
	private static ArrayList<String> parserInfo;
	
	private static final  String XML_PATH  = ".\\xmldb\\";
	private static Logger loger = Logger.getLogger("ParseFactory");
	
	private ParserFactory()
	{	
		initClassInfo();
	}

	static public ParserFactory getInstance()
	{
		if(_instance == null)
		{
			_instance = new ParserFactory();
		}
		return _instance;
	}
	
	private void initClassInfo()
	{
		parserInfo = new  ArrayList<String>();
		parserInfo.add(ParserDefine.SKILL_PARSER, "com.wly.dbc.parser.SkillParser");
		parserInfo.add(ParserDefine.SOLDIER_PARSER, "com.wly.dbc.parser.SoldierParser");
		parserInfo.add(ParserDefine.HERO_PARSER, "com.wly.dbc.parser.HeroParser");
	}
	
	public void initDBC() throws Exception
	{
		int i;
		
		for(i=ParserDefine.PARSER_ID_START; i<ParserDefine.PARSER_ID_LENGTH; i++)
		{
			parserFrom(i);
		}
	}
	
	private void parserFrom(int parserID) throws Exception
	{
		BaseParser parser;
		String parserClassName = parserInfo.get(parserID);
		try
		{
			Class cls = Class.forName(parserClassName);
			parser = (BaseParser)cls.newInstance();
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(XML_PATH+parser.getXmlFileName());
			parser.doParser(doc);
		}
		catch (ClassNotFoundException e)
		{
			loger.info("unknow class: " + parserClassName);
			e.printStackTrace();
		}
	}
}
